package com.nl.countdownclock.client;

import com.google.gwt.core.client.EntryPoint;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.canvas.client.Canvas;
import com.google.gwt.canvas.dom.client.Context2d;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Label;
import com.nl.countdownclock.client.ClockView;
import com.nl.countdownclock.client.Clock;
import java.util.Date;
import com.google.gwt.http.client.URL;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class CountdownClockApp implements EntryPoint {
	private Button clickMeButton;
	Canvas canvas;
    Context2d context;
    Clock clock;
    ClockView clockview;
    int canvasHeight;
    int canvasWidth;
    public void onModuleLoad() {
//		RootPanel rootPanel = RootPanel.get();
		RootPanel rootPanel = RootPanel.get("clockbody");
        canvas = Canvas.createIfSupported();
        
        if (canvas == null) {
              RootPanel.get().add(new Label("Sorry, your browser doesn't support the HTML5 Canvas element"));
              return;
        }
 
        rootPanel.add(canvas);
        canvas.setStyleName("maincanvas");
    	boolean countdown = true;
    	Date target = null;
    	String href = Window.Location.getHref();
    	String optionstring = null;
    	String [] splithref = href.split("\\?");
    	if(splithref.length > 1){
    		optionstring = splithref[1];
    		String[] options = optionstring.split(";");
	    	for( int i = 0; i < options.length; i++){
	    		if (options[i].toLowerCase().startsWith("countup"))
	    			countdown = false;
	    		if (options[i].toLowerCase().startsWith("target")){
	    			String targetSpec = options[i].split("=")[1];
	    			String targetFixed = URL.decode(targetSpec);
	    			target = Clock.parseTime(targetFixed);
	    		}
	    	}
    	}

    	if (target != null)
    		clock = new Clock(countdown,target);
    	else
    		clock = new Clock(countdown);
        clockview = new ClockView(canvas, clock);
        clockview.doLayout();  // as ugly as it is, this will size the canvas
 
				
	}

}
